package com.xuetang.service.impl;

import com.xuetang.entity.AdminUser;
import com.xuetang.mapper.AdminUserMapper;
import com.xuetang.service.AdminUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 管理员用户服务实现类
 */
@Service
public class AdminUserServiceImpl implements AdminUserService {

    @Autowired
    private AdminUserMapper adminUserMapper;

    @Override
    public AdminUser login(String username, String password) {
        // 对密码进行MD5加密
        String md5Password = DigestUtils.md5DigestAsHex(password.getBytes(StandardCharsets.UTF_8));
        // 查询用户
        return adminUserMapper.findByUsernameAndPassword(username, md5Password);
    }

    @Override
    public AdminUser findByUsername(String username) {
        return adminUserMapper.findByUsername(username);
    }

    @Override
    public AdminUser findById(Long id) {
        return adminUserMapper.getById(id);
    }

    @Override
    public AdminUser getById(Long id) {
        return adminUserMapper.getById(id);
    }

    @Override
    public List<AdminUser> listAll() {
        return adminUserMapper.listAll();
    }

    @Override
    public boolean add(AdminUser adminUser) {
        // 设置默认值
        adminUser.setStatus(1);
        adminUser.setCreateTime(LocalDateTime.now());
        adminUser.setUpdateTime(LocalDateTime.now());

        // 对密码进行MD5加密
        String md5Password = DigestUtils.md5DigestAsHex(adminUser.getPassword().getBytes(StandardCharsets.UTF_8));
        adminUser.setPassword(md5Password);

        return adminUserMapper.insert(adminUser) > 0;
    }

    @Override
    public boolean update(AdminUser adminUser) {
        adminUser.setUpdateTime(LocalDateTime.now());

        // 如果密码不为空，则对密码进行MD5加密
        if (adminUser.getPassword() != null && !adminUser.getPassword().isEmpty()) {
            String md5Password = DigestUtils.md5DigestAsHex(adminUser.getPassword().getBytes(StandardCharsets.UTF_8));
            adminUser.setPassword(md5Password);
        }

        return adminUserMapper.update(adminUser) > 0;
    }

    @Override
    public boolean delete(Long id) {
        return adminUserMapper.delete(id) > 0;
    }
}